package com.ex.realm;

import com.ex.common.StringUtil;
import com.ex.entity.Account;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * <h1>自定义登录的密码校验认证</h1>
 *
 * @author longdeng
 * @Date 2019/10/7 19:49
 */
@Slf4j
public class LoginCredentialsMatcher extends SimpleCredentialsMatcher {

    /**
     * 自定义密码认证器
     *
     * @param token
     * @param info
     * @return
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        /*
        token 从realm传过来的用户信息
        info 从realm传过来的自定义信息
         */
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        // 这段代码的问题
        String password = new String(t.getPassword());
        Account account = (Account) info.getPrincipals().getPrimaryPrincipal();
        boolean martch = false;
        try {
            String encodePassword = StringUtil.MD5(password, account.getSalt());
            martch = encodePassword.equals(account.getPassword());
            return martch;
        } catch (NoSuchAlgorithmException e) {
            log.info("{} -- {} -- {} -- {} ", new Date(), this.getClass().getName(), "doCredentialsMatch", "密码认证异常");
            e.printStackTrace();
        }
        log.info("{} -- {} -- {} -- {} ", new Date(), this.getClass().getName(), "doCredentialsMatch", "密码认证失败");
        return false;
    }
}
